package im.yangqiang.android.unicorn.retrofit;

import android.content.Context;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Retrofit实现
 * Created by Carlton on 16/9/18.
 */

public class HttpRetrofit
{
    private Context mContext;
    private String mBaseUrl;
    private Retrofit.Builder mBuilder = new Retrofit.Builder();
    private Retrofit retrofit;

    public HttpRetrofit(Context context, String baseUrl)
    {
        mContext = context;
        mBaseUrl = baseUrl;
        mBuilder.baseUrl(baseUrl);
        mBuilder.client(OkHttpUtils.client(context, 0));
        onBuilderCreate(mBuilder);
        retrofit = mBuilder.build();
    }

    protected void onBuilderCreate(Retrofit.Builder builder)
    {
        builder.addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create());
    }


    public <T> T create(Class<T> clazz)
    {
        return retrofit.create(clazz);
    }

    private Observable<?> mRx;

    public <T> HttpRetrofit startFlow(Observable<T> rx)
    {
        mRx = rx;
        return this;
    }

    public HttpRetrofit flow(Func1<? super Object, Observable<?>> fun1)
    {
        mRx = mRx.flatMap(fun1);
        return this;
    }

    public void endFlow(Subscriber<? super Object> subscriber)
    {
        mRx.subscribeOn(Schedulers.newThread()).observeOn(Schedulers.newThread()).subscribe(subscriber);
    }
}




